const { HttpMethods, HttpStatus } = require('../util/enum');

module.exports = rules => {
  return async function validate(ctx, next) {
    if (rules) {
      try {
        switch (ctx.method) {
          case HttpMethods.GET:
            ctx.validate(rules, ctx.query);
            break;
          case HttpMethods.POST:
            ctx.validate(rules);
            break;
        }
      } catch (error) {
        ctx.status = HttpStatus.BAD_REQUEST;
        return ctx.fail(error.errors);
      }
    }
    await next()
  }
}